package com.joe.codemother.parser;

import com.joe.codemother.ai.model.HtmlCodeResult;
import lombok.extern.slf4j.Slf4j;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class HtmlCodeParser implements CodeParser<HtmlCodeResult> {

    private static final Pattern HTML_CODE_PATTERN = Pattern.compile("```html\\s*\\n([\\s\\S]*?)```", Pattern.CASE_INSENSITIVE);


    @Override
    public HtmlCodeResult parseCode(String content) {
        HtmlCodeResult htmlCodeResult = new HtmlCodeResult();
        String s = this.extractHtmlCode(content);
        if(s != null && s.trim().length() > 0) {
            htmlCodeResult.setHtmlCode(s);
        }else  {
            htmlCodeResult.setHtmlCode(content);
        }
        return htmlCodeResult;
    }

    private String extractHtmlCode(String content) {
        Matcher matcher = HTML_CODE_PATTERN.matcher(content);
        if (matcher.find()) {
            return matcher.group(1);
        }
        log.info("The content of the html code is invalid, the code is " + content);
        return null;
    }
}
